package com.leetcode.test.binarySearch;

import org.junit.Assert;
import org.junit.Test;

public class YY题目 {

    @Test
    public void test() {
        Assert.assertEquals(6, binarySearch(new int[]{3, 4, 6, 7, 10}, 5));
        Assert.assertEquals(6, binarySearch(new int[]{6}, 5));
        Assert.assertEquals(-1, binarySearch(new int[0], 5));
        Assert.assertEquals(-1, binarySearch(null, 5));
    }

    public int binarySearch(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return -1;
        }
        if (nums.length == 1) {
            return nums[0] >= target ? nums[0] : -1;
        }

        int left = 0, right = nums.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;

            if (mid >= 1 && nums[mid] >= target && nums[mid - 1] < target) {
                return nums[mid];
            } else if (nums[left] < target) {
                left = mid + 1;
            } else if (nums[right] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }
}
